package br.com.portalaberto.connection.chain;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Form;
import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;

import br.com.portalaberto.core.UIController;

public class HttpClientThread{
	
	private String msg;
	private String pathCompleto;
	private double latitude;
	private double longitude;
	private UIController controlador;
	private HttpClient client;
	private String url;
	private String resultStr;
	
	public HttpClientThread(String pathCompleto, String msg, UIController controlador) {
		this.pathCompleto = pathCompleto;
		this.msg = msg;
		this.controlador = controlador;
	}

	public void startConn() {

		try {
			this.url = "http://localhost:8080/ServidorPortalAberto/ServidorServlet";

			byte[] imagemByte = getImageByteArray(pathCompleto);
			String imagemString = new String(imagemByte);
			this.getLocation();
			
		    client = new HttpClient();
			Handler h1 = new JSONHandler(msg,imagemString,latitude,longitude);

			client.addHandler( h1 );
			client.setUrl( url );
			//client.setRequestMethod( HttpConnection.GET );
			client.setRequestMethod( HttpConnection.POST );
			client.setParametros(imagemString);

			Worker t = new Worker ();
			t.start();
			System.out.println("iniciando a thread");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private byte[] getImageByteArray(String caminho){
		InputStream fis = null;
		FileConnection fc = null;
		byte[] imagemBytes = null;
		try	{
			fc = (FileConnection) Connector.open(caminho);
			if (!fc.exists()){
				throw new IOException("File does not exists");
			}
			int data = 0;
			fis = fc.openInputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while((data = fis.read())!=-1) {
				baos.write(data);
			}
			imagemBytes = baos.toByteArray();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				fis.close();
				fc.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return imagemBytes;
	}
	
	private void getLocation(){
		Criteria cr= new Criteria();
		cr.setHorizontalAccuracy(500);
		
		LocationProvider lp;
		Location l = null;
		Coordinates c = null;

		try {
			lp = LocationProvider.getInstance(cr);
			//timeout de 60 segundos
			l = lp.getLocation(60);
			c = l.getQualifiedCoordinates();
			if(c != null ) {
				  // Use coordinate information
				  latitude = c.getLatitude();
				  longitude = c.getLongitude();
				}
			
		} catch (LocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public String getResultStr() {
		return resultStr;
	}

	class Worker extends Thread {
		
		public void run () {
			try {
				byte [] result = client.query(null);
				sleep(10000);

				//byte [] result = null;

				//byte [] result = getImageByteArray(pathCompleto);

				if(result != null){
					resultStr = new String(result);
					//resultStr = "OK";
					System.out.println("resultado ok: "+resultStr);
				}else{
					resultStr = null;
				}
				controlador.setLiberacao(false);
			} catch (Exception e) {
				e.printStackTrace();
				resultStr = "fetch failed";
			}
		}

	}
}
